/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

function selectGPA() {
    document.getElementById('Score').style.display = 'none';
    document.getElementById('ScorePanel').style.display = 'none'; 
    document.getElementById('ScoreResult').style.display = 'none';
    document.getElementById('Ambition').style.display = 'none';
    document.getElementById('AmbitionResult').style.display = 'none';
    document.getElementById('ListSemesterRecap').style.display = 'block';
    document.getElementById('GPARecap').style.display = 'block';

}
function selectScore() {
    document.getElementById('ListSemesterRecap').style.display = 'none';
    document.getElementById('GPARecap').style.display = 'none';
    document.getElementById('Ambition').style.display = 'none';
    document.getElementById('AmbitionResult').style.display = 'none';
    document.getElementById('Score').style.display = 'block';  
    document.getElementById('ScorePanel').style.display = 'block'; 
    document.getElementById('ScoreResult').style.display = 'block';   
}
function selectAmbition() {
    document.getElementById('ListSemesterRecap').style.display = 'none';
    document.getElementById('GPARecap').style.display = 'none';
    document.getElementById('Score').style.display = 'none';
    document.getElementById('ScorePanel').style.display = 'none'; 
    document.getElementById('ScoreResult').style.display = 'none';
    document.getElementById('Ambition').style.display = 'block';
    document.getElementById('AmbitionResult').style.display = 'block';
}

//Initialization logic
function dataOnLoad_initialLoad(element){
    if(localStorage.getItem('jWelcome')=== null){
        //Set all default null json parameter
        setDefaultPassValue();
        setDefaultContentGrade();
        setDefaultValueTerm();
        setjGPAAmbitionDefaultValue();
        setjScoreDefaultValue();
        localStorage.setItem('jWelcome', 'welcome');
    }
    
}
function dataOnTheFly_initialLoad(element){
    displayGPAHeader();
    displaySemesterRecap();
    // re-compute the scrolling area
    if (bb.scroller) {
        bb.scroller.refresh();
    }
    // Remove our waiting and refresh the list
    document.getElementById('waiting').style.display = 'none';
}
//===================================================================================
//Display function
function displayGPAHeader(){
    if(localStorage.getItem('jGPARecap')== null){
        document.getElementById('GPARecap').innerHTML = "<p style=\"text-align:center\"><b>Cumulative GPA: -</b></p><p style=\"text-align:center\">You've been through 0 Semester, 0 Courses and 0 Credits.</p>";
    }
    else{
        document.getElementById('GPARecap').innerHTML = "<p style=\"text-align:center\"><b>Cumulative GPA: "+JSON.parse(localStorage.getItem('jGPARecap'))[0].gpaTotal+"</b></p><p style=\"text-align:center\">You've been through <u>"+JSON.parse(localStorage.getItem('jGPARecap'))[0].semesterTotal+" Semester(s)</u>, </br><u>"+JSON.parse(localStorage.getItem('jGPARecap'))[0].courseTotal+" Course(s)</u>, and <u>"+JSON.parse(localStorage.getItem('jGPARecap'))[0].creditTotal+" Credit(s)</u>.</p>";
    }
}

function displaySemesterRecap(){
    var json = JSON.parse(localStorage.getItem('jSemesterRecap'));
    var list = document.getElementById('ArrowListSemesterRecap'),
    curItems = list.getItems();
    var items = [],
    divSemesterItem;
    if(localStorage.getItem('jSemesterRecap') == null) {
        divSemesterItem = document.createElement('p');
        divSemesterItem.innerHTML = "-- Please Add New Course at the </br>Top-Right Corner Of this Page --";
        items.push(divSemesterItem);
        list.appendItem(divSemesterItem);
        document.getElementById('ArrowListSemesterRecap').refresh(list);
    }
    else{
        for(var i=0; i<json.length; i++) { 
            if(json[i].numberOfCourse == 0){
                continue;
            }
            var items = [],
            divSemesterItem;
            divSemesterItem = document.createElement('div');
            divSemesterItem.setAttribute('data-bb-type', 'item');
            divSemesterItem.setAttribute('data-bb-title', json[i].semesterName);
            divSemesterItem.onbtnclick = pushScreen;
            divSemesterItem.innerHTML = "GPA semester: "+json[i].gpaSemester;
            items.push(divSemesterItem);
        
            if (curItems.length > 0) {
                list.insertItemBefore(divSemesterItem, curItems[0]);
            } else {
                list.appendItem(divSemesterItem);
            }
            document.getElementById('ArrowListSemesterRecap').refresh(list);
        }
    }
}

function pushScreen(){
    var list = document.getElementById('ArrowListSemesterRecap'),
    selected = list.selected;
    bb.pushScreen('Semester.htm', 'dataOnTheFlySemester', {
        semName: selected.getTitle()
    });
//bb.pushScreen('addCourse.htm', 'dataOnTheFlyNewCourse', {semName: selected.getTitle()});
}
//===================================================================================
//Initial Value Grade & Term
function setDefaultPassValue(){
    localStorage.setItem('password', ''); 
    localStorage.setItem('passSet', 'off'); 
}

function setDefaultContentGrade(){
    localStorage.setItem('A+', '4.3');
    localStorage.setItem('A', '4');
    localStorage.setItem('A-', '3.7');
    localStorage.setItem('B+', '3.5');
    localStorage.setItem('B', '3');
    localStorage.setItem('B-', '2.7');
    localStorage.setItem('C+', '2.5');
    localStorage.setItem('C', '2');
    localStorage.setItem('D', '1');
    localStorage.setItem('E', '0');
    localStorage.setItem('F', '');
}
function setDefaultValueTerm(){
    localStorage.setItem('jSettingTerm', JSON.stringify([{
        seasonal1: 'Spring',
        seasonal2: 'Summer',
        seasonal3: 'Autumn',
        seasonal4: 'Winter'
    }]
    )
    );
}

function setjGPAAmbitionDefaultValue(){
    localStorage.setItem('jGPAAmbition', JSON.stringify([{
        currentGPA: '',
        creditsCompleted: '',
        wantedGPA: '',
        creditsLeft: '',
        ambitionResult: ''
    }]));
}

function setjScoreDefaultValue(){
    localStorage.setItem('jScoreCalculator', JSON.stringify([{
        presencePercentageWeight: '',
        presencePercentage: '',
        homeworkPercentageWeight: '',
        homeworkPercentage: '',
        projectPercentageWeight: '',
        projectPercentage: '',
        quizPercentageWeight: '',
        quizPercentage: '',
        midTestPercentageWeight: '',
        midTestPercentage: '',
        finalTestPercentageWeight: '',
        finalTestPercentage: ''
    }]));
}



// Logic Defined Function
//New Defined Function

//common Function
//append jsonObject2 to last element of jsonObject1
function appendNewData (jsonObject1, jsonObject2){
    alert('call appendNewData( obj1, obj2)');
    //get object from local json storage
    json1 = JSON.parse(JSON.stringify(jsonObject1));
    json2 = JSON.parse(JSON.stringify(jsonObject2));
    
    // concate new json object
    json1 = json1.concat(json2);
    alert('get tempJName to setItem: '+sessionStorage.getItem('tempJName'));
    localStorage.setItem(sessionStorage.getItem('tempJName'), JSON.stringify(json1));
    alert('append');
}

//sample function to add new data
function addNewData(){
    alert('call addNewData()');
    // local storage
    jName = JSON.parse(localStorage.getItem('jName2'));
    // new item 
    jName2 ={
        'numeric1': "goud", 
        'numeric2':"1", 
        'numeric3': "7", 
        "numeric4": "8"
    };
    
    //store temporary primary jName to tempJName
    sessionStorage.setItem('tempJName', 'jName2');
    alert('tempJName: '+sessionStorage.getItem('tempJName'));

    // call function appendNewData
    appendNewData(jName, jName2);
    alert('addNewData');
}

//load all local storage
function displayStorage() {
    var num, out, i, key, value;
    if (window.localStorage) {
        num = window.localStorage.length;
        if (num > 0) {
            out = "<table width='50px' cellpadding='4px' border='1px'>";
            out += "<tr width='10px'><td>Key</td><td width='50px'>Value</td></tr>";
            for (i = 0; i < num; i = i + 1) {
                key = window.localStorage.key(i);
                value = window.localStorage.getItem(key);
                out += "<tr><td width='10px'>" + key + "</td><td width='50px'>" + value + "</td></td></tr>";
            }
            out += "</table>";
            setContent("localStorage", out);
        }
    } 
}
function setContent(id, content) {
    var ele = document.getElementById(id);
    if (ele) {
        ele.innerHTML = content;
    }
}
function deleteStorage(){
    //localStorage.clear();
    localStorage.removeItem('jGPARecap');
    localStorage.removeItem('jSemesterRecap');
    localStorage.removeItem('2012-Spring');
    localStorage.removeItem('2013-Summer');
    localStorage.removeItem('2012-Autumn');
    localStorage.removeItem('2012-Summer');
    localStorage.removeItem('2013-Spring');
}


// JSON parsing get set gpaSemester semesterName --> Semester Recap
function getGPASemesterBySemesterName(json, semesterName){ 
    for (var i in json) {
        if (json[i].semesterName == semesterName) {
            return json[i].gpaSemester;
        }
    }
}
function setGPASemesterBySemesterName(json, semesterName, val) {
    for (var i in json) {
        if (json[i].semesterName == semesterName) {
            json[i].gpaSemester = val;
            break;
        }
    }
//return json; 
} 

// JSON parsing get set totalCredit semesterName --> Semester Recap
function getTotalCreditBySemesterName(json, semesterName){ 
    for (var i in json) {
        if (json[i].semesterName == semesterName) {
            return json[i].totalCredit;
        }
    }
}
function setTotalCreditBySemesterName(json, semesterName, val) {
    for (var i in json) {
        if (json[i].semesterName == semesterName) {
            json[i].totalCredit = val;
            break;
        }
    }
//return json; 
} 

// JSON parsing get set numberOfCourse semesterName --> Semester Recap
function getNumberOfCourseBySemesterName(json, semesterName){ 
    for (var i in json) {
        if (json[i].semesterName == semesterName) {
            return json[i].numberOfCourse;
        }
    }
}
function setNumberOfCourseBySemesterName(json, semesterName, val) {
    for (var i in json) {
        if (json[i].semesterName == semesterName) {
            json[i].numberOfCourse = val;
            break;
        }
    }
//return json; 
}

//Delete item on jSemesterRecap by SemesterName
function deleteItemBySemesterName(jsonName, semesterName) {
    alert("delete");
    json = JSON.parse(localStorage.getItem(jsonName));
    for(var i=0; i<json.length; i++) { 
        alert("iterate");
        if(json[i].semesterName == semesterName) {
            //json.splice(i-1,1);
            
            json[i].semesterName ="2012-Spring";
            alert (json[i].semesterName);
            localStorage.setItem('jSemesterRecap', JSON.stringify(json));
            
            alert("found");
            break;
        }
    } 
}
//Delete item on jSemesterRecap by SemesterName
function deleteItemByCourseName(jsonName, courseNameDel) {
    alert("delete");
    json = JSON.parse(localStorage.getItem(jsonName));
    for(var i=0; i<json.length; i++) { 
        alert("iterate");
        if(json[i].courseName == courseNameDel) {
            alert("found");
            //json.splice(i-1,1);
            //delete JSON.parse(localStorage.getItem(jsonName))[i];
            findAndRemove(json,courseNameDel);
            localStorage.setItem('jSemesterRecap', JSON.stringify(json));
            alert("deleted");
            break;
        }
    } 
}

function findAndRemove(array, value) {
    $.each(array, function(index, result) {
        if(result[courseName] == value) {
            //Remove from array
            array.splice(index, 1);
        }    
    });
}

//==============================================================================
//GPA AMBITION
// initialization data newAmbition
function insertNewDataAmbition(){
    localStorage.setItem('jGPAAmbition', JSON.stringify([{
        currentGPA: '3.21',
        creditsCompleted: '100',
        wantedGPA: '3.5',
        creditsLeft: '44',
        ambitionResult: '3.78'
    }]));
    
    var ambitionRes = JSON.parse(localStorage.getItem('jGPAAmbition'));
    alert(ambitionRes[0].ambitionResult);
    var gpaResult = ambitionRes[0].ambitionResult;
    document.getElementById('gpaAmbitionResult').innerHTML = gpaResult;
}

// get GPA and credits from database
function retrieveCurrentGPACredits(){
    tempGPA = JSON.parse(localStorage.getItem('jGPAAmbition'));
    var currentGPA = tempGPA[0].currentGPA;
    var creditsCompleted = tempGPA[0].creditsCompleted;
    
    //retrieve from database
    document.getElementById('inputCurrentGPA').value = JSON.parse(localStorage.getItem('jGPARecap'))[0].gpaTotal;
    document.getElementById('inputCreditsCompleted').value = JSON.parse(localStorage.getItem('jGPARecap'))[0].creditTotal;
//    document.getElementById('inputCurrentGPA').value = currentGPA;
//    document.getElementById('inputCreditsCompleted').value = creditsCompleted;
}

//calculate GPA Ambition
function calculateAmbition(){
    var cg = parseFloat(document.getElementById('inputCurrentGPA').value);
    var cc = parseFloat(document.getElementById('inputCreditsCompleted').value);
    var ag = parseFloat(document.getElementById('inputWantedGPA').value);
    var cl = parseFloat(document.getElementById('inputCreditsLeft').value);
    var gr = 0;
    if ((cg != null)&& (cc != null) &&(ag != null) && (cl != null)){
        //calculate and insert DOM element
        gr = (((cl + cc) * ag) - (cg * cc))/cl;
        document.getElementById('resultOpening').innerHTML = 'You need to achieve minimum GPA: ';
        document.getElementById('gpaAmbitionResult').innerHTML = parseFloat(gr.toFixed(2));
        document.getElementById('creditsLeft').innerHTML = 'for the '+cl+' credits left!';
        
        document.getElementById('openingText').innerHTML = "";
			
        //save to local storage
        localStorage.setItem('jGPAAmbition', JSON.stringify([{
            currentGPA: cg,
            creditsCompleted: cc,
            wantedGPA: ag,
            creditsLeft: cl,
            ambitionResult: gr
        }]));
    }
}


//==============================================================================
// Setting Page
function appendNewDataTest (){
    
    localStorage.setItem('jName', JSON.stringify([{
        numeric1: '44',
        numeric2: '2',
        numeric3: '3',
        numeric4: '4'
    },
    {
        numeric1: '134324',
        numeric2: '342',
        numeric3: '4324',
        numeric4: '23432'
    }
    ]      
    ));
    
    //set local storage from input user (new local storage)
    var jData = [{
        numeric1: '5', 
        numeric2: '6', 
        numeric3: '7', 
        numeric4: '8'
    }];
    localStorage.setItem('jName2', JSON.stringify(jData));
    
    //get object from local json storage
    var json1Object = JSON.parse(localStorage.getItem('jName'));
    var json2Object = JSON.parse(localStorage.getItem('jName2'));
    
    //get String from local json storage
    var json1String = JSON.stringify(localStorage.getItem('jName'));
    var json2String = JSON.stringify(localStorage.getItem('jName2'));

    // access object from json
    alert(json1Object[1].numeric1);
    
    var jsonArray1 = [{
        'name': "doug", 
        'id':5
    }, {
        'name': "dofug", 
        'id':23
    }];
    var jsonArray2 = [{
        'name': "goud", 
        'id':1
    }, {
        'name': "doaaug", 
        'id':52
    }];
    jsonArray1 = jsonArray1.concat(jsonArray2);
    alert (typeof jsonArray1);
    
    // concate new json object
    json1Object = json1Object.concat(json2Object);
    alert('type of jSon 1 Object: '+typeof json1Object);
    
    
    localStorage.setItem('jName3', JSON.stringify(json1Object));
    
    alert('append');
}



//functions for entering a password, setting a password, redirecting or denying access to the password setup screen, setting the secret question and answer, and reseting the password
function setPass() {
    if (mypass.value != null) {
        localStorage.setItem('password',mypass.value);
        alert (localStorage.getItem('password'));
    }
}
function changePassSetting() {
    if (passSet.value != null) {
        localStorage.setItem('passSet',passSet.value);
        alert (localStorage.getItem('passSet'));
    }
}
function checkPassSetting(){
    if(localStorage.getItem('passSet') == 'yes'){
        alert ('passSetting == yes');
        alert('Insert set password form');
    }
    else {
        alert ('passSetting unset');
        alert ('passSetting =='+localStorage.getItem('passSet'));
    }
}

//Setting Page


//show all grade
function showAllGrade(){
    var out, i, key, value;
    out = "<table width='900px' cellpadding='4px' border='1px'>";
    out += "<tr><td>Key</td><td>Value</td></tr>";
    key = 'jGrade';
    value = window.localStorage.getItem(key);
    out += "<tr><td>" + key + "</td><td>" + value + "</td></td></tr>";
    out += "</table>";
    setContent("grade", out);
}

//
function showAllTerm(){
    var out, i, key, value;
    out = "<table width='900px' cellpadding='4px' border='1px'>";
    out += "<tr><td>Key</td><td>Value</td></tr>";
    key = 'jSettingTerm';
    value = window.localStorage.getItem(key);
    out += "<tr><td>" + key + "</td><td>" + value + "</td></td></tr>";
    out += "</table>";
    setContent("term", out);
}
   
//numeric3: document.getElementById('JSONbox').value,
//accessing key properties
function jsonConcat(o1, o2) {
    for (var key in o2) {
        o1[key] = o2[key];
    }
    return o1;
}


